package com.rephilo.user.controller;

import com.rephilo.user.model.User;
import com.rephilo.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户服务
 *
 * @author rephilo
 */
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据token查询⽤用户登录邮箱接⼝
     *
     * @param token
     * @return
     */
    @GetMapping("/info/{token}")
    public String getUserByToken(@PathVariable String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        User user = userService.getUserByToken(token);
        return user.getEmail();
    }

    /**
     * 登录接⼝
     *
     * @param email
     * @param password
     * @return
     */
    @PostMapping("/login/{email}/{password}")
    public Boolean login(@PathVariable String email,
                         @PathVariable String password,
                         HttpServletResponse response) {
        String token = userService.login(email, password);
        log.info(token);
        if (StringUtils.isNotBlank(token)) {
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
            return true;
        }
        return false;
    }

    /**
     * 是否已注册
     *
     * @param email
     * @return
     */
    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable String email) {
        if (StringUtils.isBlank(email)) {
            return false;
        }

        User user = userService.getUserByEmail(email);
        return user != null;
    }

    /**
     * 注册接⼝口
     *
     * @param email
     * @param password
     * @param code
     * @return
     */
    @PostMapping("/register/{email}/{password}/{code}")
    public Boolean register(@PathVariable String email,
                            @PathVariable String password,
                            @PathVariable String code) {
        if (StringUtils.isBlank(email)) {
            return false;
        }

        if (StringUtils.isBlank(password)) {
            return false;
        }

        if (StringUtils.isBlank(code)) {
            return false;
        }

        return userService.register(email, password, code);
    }

    @GetMapping("/needLogin")
    public String needLogin() {
        return "needLogin";
    }
}
